<template>
  <el-dialog v-if="load" :close-on-click-modal="false" title="申请付款" v-model="visible" align-center width="1300px"
    :z-index="2000" @close="handleClose">
    <el-form ref="formRef" :model="form" label-width="110px">
      <div class="v-title mb-3">基础信息</div>
      <div class="grid grid-cols-4 gap-x-3">
        <el-form-item label="供应商">
          <el-input v-model="form.basic.supplier_name" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item label="供应商类型">
          <VSelect v-model="form.basic.purchase_type" placeholder="请选择" :options="options.purchase_type || []" filterable
            clearable disabled />
        </el-form-item>
        <el-form-item label="结算方式">
          <el-input v-model="form.basic.period_name" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item label="公司主体">
          <VSelect v-model="form.basic.company_id" placeholder="请选择" :options="options.company_id || []" filterable
            clearable disabled />
        </el-form-item>
        <el-form-item label="交易方式">
          <VSelect v-model="form.basic.payment_type" placeholder="请选择" :options="options.payment_type || []" filterable
            clearable disabled />
        </el-form-item>
        <el-form-item label="支付账号">
          <VSelect v-model="form.basic.payment_account" placeholder="请选择" :options="options.alipay_account || []"
            filterable clearable disabled />
        </el-form-item>
        <el-form-item label="支付币种">
          <VSelect v-model="form.basic.currency" placeholder="请选择" :options="options.currency || []" filterable clearable
            disabled />
        </el-form-item>
        <el-form-item label="收款人" prop="basic.collect_name"
          :rules="[{ required: form.basic.payment_type!==1, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.basic.collect_name" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="收款账号" prop="basic.collect_account"
          :rules="[{ required: form.basic.payment_type!==1, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.basic.collect_account" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="银行名称" prop="basic.collect_bank"
          :rules="[{ required: form.basic.payment_type!==1, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.basic.collect_bank" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="期望付款时间" prop="basic.except_payment_time"
          :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-date-picker v-model="form.basic.except_payment_time" type="date" value-format="YYYY-MM-DD"
            placeholder="结束日期" />
        </el-form-item>
        <el-form-item label="申请付款类型" prop="basic.apply_payment_type"
          :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.basic.apply_payment_type" placeholder="请选择" :options="apply_payment_type" filterable
            clearable @change="paymentTypeChange" />
        </el-form-item>
        <el-form-item label="申请付款金额" prop="basic.apply_price"
          :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-input-number v-model="form.basic.apply_price" controls-position="right" :step="0.01" :precision="2"
            class="w-full" />
        </el-form-item>
        <el-form-item label="优惠">
          <el-input-number v-model="form.basic.discount_price" controls-position="right" :step="0.01" :precision="2"
            disabled class="w-full" />
        </el-form-item>
        <el-form-item label="售后">
          <el-input-number v-model="form.basic.after_sale_price" controls-position="right" :step="0.01" :precision="2"
            placeholder="优惠" class="w-full" />
        </el-form-item>
        <el-form-item label="折扣">
          <el-input-number v-model="form.basic.preferential_price" controls-position="right" :step="0.01" :precision="2"
            placeholder="优惠" class="w-full" />
        </el-form-item>
        <el-form-item label="飞书审核">
          <div class="flex items-center gap-3 mb-4">
            <el-switch v-model="form.basic.is_feishu_audit" inline-prompt active-text="是" inactive-text="否"
              :active-value="2" :inactive-value="1" />
            <div class="text-green-600 text-xs">提示：启用后只能在飞书审核</div>
          </div>
        </el-form-item>
        <el-form-item label="备注" class="col-span-full">
          <el-input v-model="form.basic.remark" placeholder="备注" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" />
        </el-form-item>
        <div class="col-span-full mb-2">
          <VUpload v-model="form.basic.attachment" title="采购附件" :disabled="isPay" multiple
            :types="['jpg', 'jpeg', 'png', 'xlsx', 'xml', 'pdf']">
            图片类型只能是jpg/png/jpeg/xml/xlsx/pdf，不超过5M
          </VUpload>
        </div>
      </div>
      <div class="v-title mb-3 mt-2 flex">
        <div class="flex-1">采购单信息</div>
        <div><VText title="申请付款总金额" :value="XEUtils.toFixed(form.purchase.reduce((acc, cur) => acc + cur.apply_price, 0),2)" class="ml-auto" /></div>
      </div>
      <vxe-table ref="tableRef" :data="form.purchase" size="small">
        <vxe-column title="采购单号" :min-width="140" fixed="left">
          <template #default="{ row }">
            <VText :value="row.purchase_no" />
          </template>
        </vxe-column>
        <vxe-column title="sku" field="sku" :min-width="100" fixed="left" />
        <vxe-column title="产品名称" field="sku_cn_title" :min-width="180">
          <template #default="{ row }">
            <VText :value="row.sku_cn_title" :line="2" />
          </template>
        </vxe-column>
        <vxe-column title="下单数量" field="purchase_num" :min-width="100" />
        <vxe-column title="下单金额" field="unit_price" :min-width="100">
          <template #default="{ row }">
            <div><span class='text-gray-500'></span>{{ row.is_drawback === 2 ?
              row.total_purchase_price_tax :
              row.total_purchase_price }}</div>
          </template>
        </vxe-column>
        <vxe-column title="运费" field="tracking_price" :min-width="80" />
        <vxe-column title="优惠" field="discount_price" :min-width="80" />
        <vxe-column title="折扣" field="preferential_price" :min-width="80" />
        <vxe-column title="售后" field="after_sale_price" :min-width="80" />
        <vxe-column title="入库数量" field="inbound_num" :min-width="80" />
        <vxe-column title="入库金额" field="inbound_price" :min-width="80" />
        <vxe-column title="库内退货数量" :min-width="110">
          <template #header>库内退货数量<br>库内退货金额</template>
          <template #default="{ row }">
            <div><span class='text-gray-500'>数量: </span>{{ row.return_num }}</div>
            <div><span class='text-gray-500'>金额: </span>{{ row.return_price }}</div>
          </template>
        </vxe-column>
        <vxe-column title="退款金额" field="refund_price" :min-width="80" />
        <vxe-column title="待申请付款金额" field="wait_apply_price" :min-width="80" />
        <vxe-column title="已申请未付款金额" field="wait_payment_price" :min-width="80" />
        <vxe-column title="已申请未付款运费" field="wait_payment_tracking_price" :min-width="80" />
        <vxe-column title="已付金额" field="payment_price" :min-width="80" />
        <vxe-column title="申请付款金额" :min-width="110" fixed="right">
          <template #default="{ row }">
            <el-input-number v-model="row.apply_price" :controls="false" :step="0.01" :precision="2" class="w-full" />
          </template>
        </vxe-column>
        <vxe-column title="最后结算日期" field="start_payment_time" :min-width="110" fixed="right" />
      </vxe-table>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings[2]" @click="create(2)">确 定</el-button>
      <el-button type="primary" :loading="loadings[1]" @click="create(1)">提 交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus'
import XEUtils from 'xe-utils'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})

// 表单处理
const formRef = ref()
const form = ref({})

// 申请付款类型 options
const apply_payment_type = computed(() => {
  if (!form.value.basic || !props.options.apply_payment_type) return []
  return ![1].includes(form.value.basic.purchase_type) ? props.options.apply_payment_type.slice(0, 2) : props.options.apply_payment_type.slice(2)
})

// 重置付款金额
const setPrice = (reset) => {
  form.value.basic.apply_price = reset ? 0 : form.value.basic.wait_apply_price
  form.value.purchase.forEach(d => {
    d.apply_price = reset ? 0 : d.wait_apply_price
  })
}
const paymentTypeChange = ({ value }) => {
  setPrice(value === 2)
}


// 打开弹窗
const open = async (p_ids) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = {
    basic: {},
    purchase: [],
  }
  loadings = reactive({})
  formRef?.value?.resetFields()

  try {
    const res = await api.selectDetail({ p_ids })
    form.value = res.data
  } catch (error) {
    return
  }
  form.value.basic.wait_apply_price = form.value.basic.apply_price
  form.value.purchase.forEach(d => {
    d.apply_price = d.wait_apply_price
  })
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const create = async (is_submit) => {
  const validator = await formRef?.value.validate()
  if (!validator) return
  loadings[is_submit] = true
  form.value.basic.is_submit = is_submit
  api.applyPayment(form.value).then(res => {
    ElMessage.success('操作成功')
    emit('success')
    close()
  }).finally(() => {
    loadings[is_submit] = false
  })
}

defineExpose({ open })
</script>